import React, {FunctionComponent} from "react";
import {XiTableInterface} from "./XiTableInterface";
import {Table} from "antd";
import {Get, Post, UUIDGenerator} from "para-lib";
import ButtonTools from "../Layout/ButtonTools";
import Svg from "./Svg";
import "./index.less";

const XiTable: FunctionComponent<XiTableInterface> = (props) => {
    const {
        bordered = true,
        method,
        url,
        params,
        headers,
        queryCallback,
        size,
        search,
        buttonToolsDataSource,
        onButtonToolsClick,
        columns,
        showHeader = true,
        refresh = 0,
        rightExtra,
        rowKey,
        ...rest
    } = props;

    const keyRef: any = React.useRef(UUIDGenerator() || "1");
    const [cusParams, setCusParams] = React.useState<any>({page: 1, size, cond: ""});
    const [total, setTotal] = React.useState<number>(0);
    const [loading, setLoading] = React.useState<boolean>(false);
    const [dataSource, setDataSource] = React.useState<any[]>([]);
    const [refreshSelf, setRefreshSelf] = React.useState<number>(0);
    const ref: any = React.createRef();

    const GetFloatPage = (container: any) => {
        if (container) {
            const {height} = container.parentNode.getBoundingClientRect();
            const floatPages = Math.round((height - 120 - 48) / 40); // 动态计算表格高度最合适的分页数据
            return floatPages > 0 ? floatPages : 25;
        }
    };
    const PaginationOnChange = (page: any, size: any) => {
        setCusParams({page, size});
    };
    const PaginationOnShowChange = (current: any, size: any) => {
        setCusParams({size: size});
    };
    const onButtonTools = (info: any) => {
        if (info.type === "search") {
            return setCusParams({...cusParams, cond: info.value});
        } else if (info.type === "advancedSearch") {

        } else {
            return onButtonToolsClick && onButtonToolsClick(info);
        }
    };
    const renderHeader = () => {
        return <ButtonTools from={"table"} search={search}
                            dataSource={buttonToolsDataSource}
                            rightExtra={rightExtra}
                            onClick={onButtonTools}
        />;
    };
    const getScrollHeight = () => {
        if (!cusParams.size) return 0;
        let h = cusParams.size * 39;
        const card: any = document.querySelector(`.xi-table-${keyRef.current}`);
        const parentNode = card?.parentNode;
        if (!parentNode) return h;
        const parentH = parentNode.getBoundingClientRect().height;
        if (h > parentH) h = parentH - 182;
        return h;
    };
    const getTableLayoutHeight = () => {
        if (showHeader) {
            return "calc(100vh - 56px - 58px - 48px - 48px)";
        } else {
            return "calc(100vh - 56px - 58px - 48px)";
        }
    };
    React.useEffect(() => {
        /* 获取请求数据 */
        // if (refresh === 0) return;
        const QueryFetch = async () => {
            setLoading(true);
            let response: any;
            if (ref.current && !cusParams.size) { // 如果不存在size，就返回，用自己计算高度来匹配
                setCusParams({...cusParams, size: GetFloatPage(ref.current)});
                return;
            }
            if (method === "Get") response = await Get({url, params: Object.assign({}, cusParams, params), headers});
            if (method === "Post") response = await Post({url, data: Object.assign({}, cusParams, params), headers});
            let {data, err} = response;
            if (err) {
                setLoading(false);
                setDataSource([]);
                setTotal(0);
                return;
            }
            if (queryCallback) {
                const nData = queryCallback(data.data);
                if (nData) data = nData;
            } else {
                // 判断是否是分页数据还是全量数据
                if (Array.isArray(data?.data)) { // 不分页数据
                    data = data?.data;
                } else if (typeof data?.data === "object") { // 分页数据
                    data = data?.data?.list;
                } else { // 数据异常情况
                    data = [];
                }
            }
            data.forEach((item: any) => {
                for (let key in item) {
                    if (typeof item[key] === "object") {
                        item[key] = JSON.stringify(item[key]);
                    }
                }
            });
            setLoading(false);
            setDataSource(data || []);
            setTotal(response?.data?.data?.total || 0);
        };
        QueryFetch();
    }, [cusParams, refresh, refreshSelf]);

    React.useEffect(() => {
        setRefreshSelf(Math.random());
    }, [params]);

    React.useEffect(() => {
        if (ref.current) {
            const layout: any = document.querySelector(`.xi-table-layout-${keyRef.current} .ant-table`);
            layout?.setAttribute("style", `height: ${getTableLayoutHeight()}`);
        }
    }, [ref]);

    return (
        <div className={`xi-table xi-table-${keyRef.current}`} ref={ref}>
            <Table columns={columns} dataSource={dataSource} loading={loading}
                   size={"small"} className={`xi-table-layout-${keyRef.current}`}
                // title={renderHeader}
                   showHeader={showHeader}
                   locale={{
                       emptyText: () => <div className={"table-empty"}>
                           <Svg/>
                           {/*<div>暂无数据</div>*/}
                       </div>
                   }}
                   pagination={dataSource.length ? {
                       position: ["bottomRight"],
                       pageSize: cusParams.size,
                       size: "small",
                       showSizeChanger: true,
                       showQuickJumper: true,
                       showTotal: (total: number) => `共${total}条`,
                       defaultPageSize: cusParams.size,
                       defaultCurrent: 1,
                       responsive: true,
                       showTitle: true,
                       total: total,
                       onChange: PaginationOnChange,
                       onShowSizeChange: PaginationOnShowChange
                   } : false}
                   bordered={bordered}
                   scroll={{y: getScrollHeight()}} rowKey={rowKey || "id"}
                   {...rest}
            />
        </div>
    );
};

export default XiTable;
